import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { settingsApi } from "@/api/services";
import type {
  UserSettings,
  ThemeSettings,
  NotificationSettings,
  PrivacySettings,
  ChatSettings,
} from "@/types/settings";

export const useSettingsStore = defineStore(
  "settings",
  () => {
    // 状态
    const settings = ref<UserSettings>({
      theme: {
        mode: "auto", // 'light' | 'dark' | 'auto'
        primaryColor: "#1976d2",
        fontSize: "medium", // 'small' | 'medium' | 'large'
        fontFamily: "system",
        borderRadius: "medium", // 'small' | 'medium' | 'large'
        compactMode: false,
        animations: true,
        customCss: "",
      },
      notifications: {
        enabled: true,
        sound: true,
        desktop: true,
        email: false,
        push: true,
        messageNotifications: true,
        systemNotifications: true,
        marketingEmails: false,
        weeklyDigest: true,
        soundVolume: 0.5,
        notificationTime: {
          start: "09:00",
          end: "22:00",
        },
      },
      privacy: {
        profileVisibility: "public", // 'public' | 'friends' | 'private'
        showOnlineStatus: true,
        allowDirectMessages: true,
        shareUsageData: false,
        personalizedAds: false,
        dataRetention: 365, // days
        twoFactorAuth: false,
        sessionTimeout: 30, // minutes
      },
      chat: {
        autoSave: true,
        messageHistory: true,
        showTimestamps: true,
        showReadReceipts: true,
        enterToSend: true,
        showTypingIndicator: true,
        messagePreview: true,
        autoScrollToBottom: true,
        maxMessageLength: 4000,
        attachmentMaxSize: 10, // MB
        allowedFileTypes: ["image/*", "text/*", "application/pdf"],
        defaultPersona: null,
        streamingResponse: true,
        codeHighlighting: true,
        mathRendering: true,
        emojiShortcuts: true,
      },
      language: "zh-CN",
      timezone: "Asia/Shanghai",
      dateFormat: "YYYY-MM-DD",
      timeFormat: "24h", // '12h' | '24h'
      currency: "CNY",
      autoBackup: true,
      backupFrequency: "daily", // 'daily' | 'weekly' | 'monthly'
      exportFormat: "json", // 'json' | 'csv' | 'xml'
      debugMode: false,
      betaFeatures: false,
    });

    const isLoading = ref(false);
    const lastSyncTime = ref<Date | null>(null);
    const isDirty = ref(false);
    const syncStatus = ref<"idle" | "syncing" | "success" | "error">("idle");

    // 计算属性
    const themeSettings = computed(() => settings.value.theme);
    const notificationSettings = computed(() => settings.value.notifications);
    const privacySettings = computed(() => settings.value.privacy);
    const chatSettings = computed(() => settings.value.chat);

    const isDarkMode = computed(() => {
      if (settings.value.theme.mode === "auto") {
        return window.matchMedia("(prefers-color-scheme: dark)").matches;
      }
      return settings.value.theme.mode === "dark";
    });

    const isLightMode = computed(() => !isDarkMode.value);

    const currentLanguage = computed(() => settings.value.language);
    const currentTimezone = computed(() => settings.value.timezone);

    const notificationsEnabled = computed(
      () => settings.value.notifications.enabled,
    );
    const soundEnabled = computed(() => settings.value.notifications.sound);

    const isCompactMode = computed(() => settings.value.theme.compactMode);
    const animationsEnabled = computed(() => settings.value.theme.animations);

    const canReceiveNotifications = computed(() => {
      const now = new Date();
      const currentTime = now.getHours() * 60 + now.getMinutes();
      const startTime = parseTime(
        settings.value.notifications.notificationTime.start,
      );
      const endTime = parseTime(
        settings.value.notifications.notificationTime.end,
      );

      if (startTime <= endTime) {
        return currentTime >= startTime && currentTime <= endTime;
      } else {
        // 跨天的情况
        return currentTime >= startTime || currentTime <= endTime;
      }
    });

    const maxFileSize = computed(
      () => settings.value.chat.attachmentMaxSize * 1024 * 1024,
    ); // bytes

    const hasUnsavedChanges = computed(() => isDirty.value);

    // 辅助函数
    const parseTime = (timeStr: string): number => {
      const [hours, minutes] = timeStr.split(":").map(Number);
      return hours * 60 + minutes;
    };

    // 方法
    const loadSettings = async () => {
      try {
        isLoading.value = true;
        const response = await settingsApi.getUserSettings();
        settings.value = { ...settings.value, ...response.data };
        lastSyncTime.value = new Date();
        isDirty.value = false;
        syncStatus.value = "success";
        return response;
      } catch (error) {
        syncStatus.value = "error";
        throw error;
      } finally {
        isLoading.value = false;
      }
    };

    const saveSettings = async (settingsToSave?: Partial<UserSettings>) => {
      try {
        isLoading.value = true;
        syncStatus.value = "syncing";

        const dataToSave = settingsToSave || settings.value;
        const response = await settingsApi.updateUserSettings(dataToSave);

        if (settingsToSave) {
          // 部分更新
          Object.assign(settings.value, settingsToSave);
        }

        lastSyncTime.value = new Date();
        isDirty.value = false;
        syncStatus.value = "success";

        return response;
      } catch (error) {
        syncStatus.value = "error";
        throw error;
      } finally {
        isLoading.value = false;
      }
    };

    const updateTheme = async (themeUpdates: Partial<ThemeSettings>) => {
      settings.value.theme = { ...settings.value.theme, ...themeUpdates };
      isDirty.value = true;

      // 立即应用主题变化
      applyTheme();

      // 自动保存主题设置
      await saveSettings({ theme: settings.value.theme });
    };

    const updateNotifications = async (
      notificationUpdates: Partial<NotificationSettings>,
    ) => {
      settings.value.notifications = {
        ...settings.value.notifications,
        ...notificationUpdates,
      };
      isDirty.value = true;
      return saveSettings({ notifications: settings.value.notifications });
    };

    const updatePrivacy = async (privacyUpdates: Partial<PrivacySettings>) => {
      settings.value.privacy = { ...settings.value.privacy, ...privacyUpdates };
      isDirty.value = true;
      return saveSettings({ privacy: settings.value.privacy });
    };

    const updateChat = async (chatUpdates: Partial<ChatSettings>) => {
      settings.value.chat = { ...settings.value.chat, ...chatUpdates };
      isDirty.value = true;
      return saveSettings({ chat: settings.value.chat });
    };

    const updateLanguage = async (language: string) => {
      settings.value.language = language;
      isDirty.value = true;
      return saveSettings({ language });
    };

    const updateTimezone = async (timezone: string) => {
      settings.value.timezone = timezone;
      isDirty.value = true;
      return saveSettings({ timezone });
    };

    const toggleDarkMode = async () => {
      const newMode = isDarkMode.value ? "light" : "dark";
      await updateTheme({ mode: newMode });
    };

    const toggleCompactMode = async () => {
      await updateTheme({ compactMode: !settings.value.theme.compactMode });
    };

    const toggleAnimations = async () => {
      await updateTheme({ animations: !settings.value.theme.animations });
    };

    const toggleNotifications = async () => {
      await updateNotifications({
        enabled: !settings.value.notifications.enabled,
      });
    };

    const toggleSound = async () => {
      await updateNotifications({ sound: !settings.value.notifications.sound });
    };

    const resetSettings = async () => {
      try {
        await settingsApi.resetUserSettings();
        await loadSettings();
      } catch (error) {
        throw error;
      }
    };

    const exportSettings = async (format: "json" | "csv" | "xml" = "json") => {
      try {
        const response = await settingsApi.exportSettings(format);
        return response.data;
      } catch (error) {
        throw error;
      }
    };

    const importSettings = async (
      settingsData: any,
      format: "json" | "csv" | "xml" = "json",
    ) => {
      try {
        const response = await settingsApi.importSettings(settingsData, format);
        settings.value = { ...settings.value, ...response.data };
        isDirty.value = false;
        lastSyncTime.value = new Date();

        // 应用导入的设置
        applyTheme();

        return response;
      } catch (error) {
        throw error;
      }
    };

    const validateSettings = (settingsToValidate: Partial<UserSettings>) => {
      const errors: string[] = [];

      // 验证主题设置
      if (settingsToValidate.theme) {
        const { fontSize, borderRadius, mode } = settingsToValidate.theme;
        if (fontSize && !["small", "medium", "large"].includes(fontSize)) {
          errors.push("Invalid font size");
        }
        if (
          borderRadius &&
          !["small", "medium", "large"].includes(borderRadius)
        ) {
          errors.push("Invalid border radius");
        }
        if (mode && !["light", "dark", "auto"].includes(mode)) {
          errors.push("Invalid theme mode");
        }
      }

      // 验证隐私设置
      if (settingsToValidate.privacy) {
        const { profileVisibility, dataRetention, sessionTimeout } =
          settingsToValidate.privacy;
        if (
          profileVisibility &&
          !["public", "friends", "private"].includes(profileVisibility)
        ) {
          errors.push("Invalid profile visibility");
        }
        if (dataRetention && (dataRetention < 1 || dataRetention > 3650)) {
          errors.push("Data retention must be between 1 and 3650 days");
        }
        if (sessionTimeout && (sessionTimeout < 5 || sessionTimeout > 1440)) {
          errors.push("Session timeout must be between 5 and 1440 minutes");
        }
      }

      // 验证聊天设置
      if (settingsToValidate.chat) {
        const { maxMessageLength, attachmentMaxSize } = settingsToValidate.chat;
        if (
          maxMessageLength &&
          (maxMessageLength < 1 || maxMessageLength > 10000)
        ) {
          errors.push(
            "Max message length must be between 1 and 10000 characters",
          );
        }
        if (
          attachmentMaxSize &&
          (attachmentMaxSize < 1 || attachmentMaxSize > 100)
        ) {
          errors.push("Attachment max size must be between 1 and 100 MB");
        }
      }

      return errors;
    };

    const applyTheme = () => {
      const root = document.documentElement;
      const theme = settings.value.theme;

      // 应用主题模式
      if (theme.mode === "auto") {
        const prefersDark = window.matchMedia(
          "(prefers-color-scheme: dark)",
        ).matches;
        root.setAttribute("data-theme", prefersDark ? "dark" : "light");
      } else {
        root.setAttribute("data-theme", theme.mode);
      }

      // 应用主色调
      root.style.setProperty("--primary-color", theme.primaryColor);

      // 应用字体大小
      const fontSizeMap = {
        small: "14px",
        medium: "16px",
        large: "18px",
      };
      root.style.setProperty("--base-font-size", fontSizeMap[theme.fontSize]);

      // 应用边框圆角
      const borderRadiusMap = {
        small: "4px",
        medium: "8px",
        large: "12px",
      };
      root.style.setProperty(
        "--border-radius",
        borderRadiusMap[theme.borderRadius],
      );

      // 应用紧凑模式
      root.classList.toggle("compact-mode", theme.compactMode);

      // 应用动画设置
      root.classList.toggle("no-animations", !theme.animations);

      // 应用自定义CSS
      let customStyleElement = document.getElementById("custom-theme-styles");
      if (!customStyleElement) {
        customStyleElement = document.createElement("style");
        customStyleElement.id = "custom-theme-styles";
        document.head.appendChild(customStyleElement);
      }
      customStyleElement.textContent = theme.customCss || "";
    };

    const requestNotificationPermission = async () => {
      if ("Notification" in window) {
        const permission = await Notification.requestPermission();
        if (permission === "granted") {
          await updateNotifications({ desktop: true });
        } else {
          await updateNotifications({ desktop: false });
        }
        return permission;
      }
      return "denied";
    };

    const testNotification = () => {
      if (
        settings.value.notifications.enabled &&
        settings.value.notifications.desktop
      ) {
        new Notification("测试通知", {
          body: "这是一条测试通知消息",
          icon: "/favicon.ico",
        });
      }
    };

    const getBackupSettings = () => {
      return {
        autoBackup: settings.value.autoBackup,
        backupFrequency: settings.value.backupFrequency,
        exportFormat: settings.value.exportFormat,
      };
    };

    const updateBackupSettings = async (backupSettings: {
      autoBackup?: boolean;
      backupFrequency?: "daily" | "weekly" | "monthly";
      exportFormat?: "json" | "csv" | "xml";
    }) => {
      Object.assign(settings.value, backupSettings);
      isDirty.value = true;
      return saveSettings(backupSettings);
    };

    const enableBetaFeatures = async () => {
      settings.value.betaFeatures = true;
      isDirty.value = true;
      return saveSettings({ betaFeatures: true });
    };

    const disableBetaFeatures = async () => {
      settings.value.betaFeatures = false;
      isDirty.value = true;
      return saveSettings({ betaFeatures: false });
    };

    const toggleDebugMode = async () => {
      settings.value.debugMode = !settings.value.debugMode;
      isDirty.value = true;
      return saveSettings({ debugMode: settings.value.debugMode });
    };

    // 初始化
    const initializeSettings = async () => {
      try {
        await loadSettings();
        applyTheme();

        // 监听系统主题变化
        if (settings.value.theme.mode === "auto") {
          const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
          mediaQuery.addEventListener("change", applyTheme);
        }
      } catch (error) {
        // 使用默认设置
        applyTheme();
      }
    };

    return {
      // 状态
      settings,
      isLoading,
      lastSyncTime,
      isDirty,
      syncStatus,

      // 计算属性
      themeSettings,
      notificationSettings,
      privacySettings,
      chatSettings,
      isDarkMode,
      isLightMode,
      currentLanguage,
      currentTimezone,
      notificationsEnabled,
      soundEnabled,
      isCompactMode,
      animationsEnabled,
      canReceiveNotifications,
      maxFileSize,
      hasUnsavedChanges,

      // 方法
      loadSettings,
      saveSettings,
      updateTheme,
      updateNotifications,
      updatePrivacy,
      updateChat,
      updateLanguage,
      updateTimezone,
      toggleDarkMode,
      toggleCompactMode,
      toggleAnimations,
      toggleNotifications,
      toggleSound,
      resetSettings,
      exportSettings,
      importSettings,
      validateSettings,
      applyTheme,
      requestNotificationPermission,
      testNotification,
      getBackupSettings,
      updateBackupSettings,
      enableBetaFeatures,
      disableBetaFeatures,
      toggleDebugMode,
      initializeSettings,
    };
  },
  {
    persist: {
      key: "settings-store",
      paths: ["settings", "lastSyncTime"],
      storage: localStorage,
    },
  },
);
